import axios, { AxiosResponse, } from "axios";
import Message from "@/api/Message";
import qs from 'qs';
import { message } from "ant-design-vue";
import { Storage } from "@/utils/Storage";
import router from "@/router/index";
import { LOGIN_NAME } from "@/router/constant";
import { useUserStore } from '@/store/modules/user';
const messageInstance = Message();
const tokenKey = "token";
const TIME_OUT = 1400000;
//创建请求实例，设置基础配置
export const request = axios.create({
  baseURL: import.meta.env.VITE_APP_API_PREFIX as string,
  timeout: TIME_OUT,
  headers: {
    "Content-Type": "application/json",
    // 'Content-Type': 'application/x-www-form-urlencoded'
    // 'Content-Type': 'multipart/form-data;  boundary=----WebKitFormBoundary2aXQlWf6Ry3KweQt'
    // 'token': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyNzE3NGRmMGI0MzU0NTI3ODQzYTAzMmJjYmI5YWVmMyIsInN1YiI6IntcInVzZXJJZFwiOjIxNzIsXCJ1c2VyTmFtZVwiOlwic3lzdGVtXCIsXCJsb2dpblRhcmdldFwiOlwiYWRtaW5cIn0iLCJpc3MiOiJzZyIsImlhdCI6MTY3Mjk2ODE2MCwiZXhwIjoxNjcyOTcyNjYwfQ.4-_Shz0z3IFmO-EBQ_GzI6qPAhWr1iVHm_AWVk1Wxz4',
    "Redirect-Header": false,
  },
});

/**
 * 设置header属性，后续可以在这里设置token什么的
 * @returns
 */
const baseHeader = () => {
  const token = Storage.get("ACCESS_TOKEN", null);
  const userStore = useUserStore();
  return {
    [tokenKey]: token,
    'Site-Id': userStore.userInfo.siteId
  };
};
let judgArr = function (params: any) {
  let res = false;
  if (params instanceof Object) {
    Object.keys(params).forEach(key => {
      if (Array.isArray(params[key])) {
        res = true;
      }
    })
  }
  return res;
}

/**
 * 获取cookie处理成对象返回方便获取cookie中的数据
 * @returns
 */
const initCookieInstance = () => {
  return {};
};
initCookieInstance();

request.interceptors.request.use(
  (config: any) => {
    let url = config.url;
    if (!config.url.includes('server-admin')) {
      config.url = 'http://api.jeecms.com' + url;
    }
    config.headers = Object.assign({}, baseHeader(), config.headers, { 'Router-Id': sessionStorage.routerID });
    // 检查url
    if (!config.url) {
      messageInstance.error("请传入");
    }

    if (config.method == 'get' && config.params !== null) {
      let result = judgArr(config.params);
      if (result) {
        config.paramsSerializer = { //
          indexes: null // by default: false
        }
      }
    }
    //config.data = qs.stringify(config.data, {indices: false})
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
/**
 * 响应拦截
 */
request.interceptors.response.use(
  (response: any) => {
    const ex = 7 * 24 * 60 * 60 * 1000;
    response.headers?.token
      ? Storage.set("ACCESS_TOKEN", response.headers.token, ex)
      : "";
    if (response.config.url.endsWith("/authorizations/product")) {
      let productAppId = response.data ? response.data.data.productAppId : "";
      let productObj = response.data ? response.data.data : {};
      window.localStorage.setItem("productAppId", productAppId);
      window.localStorage.setItem("mobile", productObj.mobile);
      window.localStorage.setItem("version", productObj.version);
      window.localStorage.setItem(
        "productAppId" + productObj.mobile,
        productObj.productAppId
      );
    }
    return response;
  },
  (error) => {
    let { message } = error;
    if (error.response.status === 401 && router.currentRoute.value.path !== '/login') {
      // 判断状态码是401 跳转到登录
      router.push({
        name: LOGIN_NAME,
        query: {
          redirect: router.currentRoute.value.fullPath || "/",
        },
      });
      message = "请重新登录";
    }
    if (error.response.status === 404) {
      message = "接口不存在";
    }
    if (error.response.status === 500) {
      message = "服务端错误";
    }
    // messageInstance.error(message);
    return Promise.reject(error);
  }
);
/**
 * 检查返回数据
 * @param response
 * @returns
 */
const checkRes = async (response: AxiosResponse<any, any>) => {
  return response;
};
export interface RequestData {
  [k: string]: any;
}
export interface Headers {
  [k: string]: string;
}
/**
 * 发起post请求
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export const post = async (url: string, data: RequestData) => {
  let res = await request({
    method: "post",
    url,
    data,
  });
  res = await checkRes(res);
  return res.data;
};
/**
 * 发起get请求
 * @param url 接口地址
 * @param data 参数
 * @param headers 自定义的header
 * @returns
 */
export const get = async (
  url: string,
  data: RequestData,
  headers: Headers = {}
) => {
  let res = await request.get(url, {
    params: data,
    headers
  });
  let response: RequestData = await checkRes(res);
  if (response.data.code == "00000 00000") {
    return res.data.data;
  } else {
    message.error(response.data.message);
    return false;
  }
};
export const get_file = async (
  url: string,
  data: RequestData,
  _headers: Headers = {}
) => {
  let res = await request({
    method: "get",
    url,
    responseType: "blob",
    params: data,
  });
  let resData = res.data;
  console.log(res, "res.headers['content - disposition']");
  if (res.headers['content-disposition']) {
    resData['content-disposition'] = res.headers['content-disposition'].split('=')[1];
  }
  return resData
};

/**
 * 发起upload请求
 * @param url 接口地址
 * @param data 参数
 * @param onUploadProgress 自定义的onUploadProgress
 * @returns
 */
export const upload = async (url: string, data: RequestData) => {
  let res = await request({
    method: "post",
    url,
    headers: {
      "Content-Type":
        "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
    },
    data,
    timeout: 0,
  });
  res = await checkRes(res);
  return res.data;
};

export const download = async (url: string, data: RequestData, _headers: Headers = {}) => {
  let res = await request({
    method: "post",
    url,
    responseType: "blob",
    data
  });
  let resData = res.data
  if(res.headers['content-disposition']) {
    resData['content-disposition'] = decodeURIComponent(res.headers['content-disposition'].split('=')[1])
    
  }
  return resData
};

/**
 * login
 * @param url 接口地址
 * @param data 参数
 * @param login login
 * @returns
 */
export const login = async (url: string, data: RequestData) => {
  let res = await request({
    method: "post",
    url,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data,
    timeout: 0,
  });
  res = await checkRes(res);
  return res.data;
};
